import heapq

from querier.esquerier import ElasticSearchQuerier
import json
import operator

DICT_CONTENT_TYPE = {
    '1': 'text',
    '2': 'video',
    '3': 'image'
}


class WeiboContentTypeTagsQuerier(ElasticSearchQuerier):

    def __init__(self, es, index, doc_type):
        super(WeiboContentTypeTagsQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def search(self, args):
        id_ = args.get('user_id')
        if not id_:
            return {'message': 'user_id is needed'}

        res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
        if res['found']:
            content_types = res['_source']['content_type']
            weight = res['_source']['content_type_weight']
            len_content_types = len(content_types)
            len_weight = len(weight)
            s = sum(weight)
            length = len_content_types if len_content_types <= len_weight else len_weight

            ret = [{"text": DICT_CONTENT_TYPE.get(content_types[i]), "weight": weight[i]/s} for i in range(0, length)]

            return {'tags': ret}

        return {'message': 'user_id=%s not found.' % id_}

    def _build_query(self, args):
        pass

    def _build_result(self, es_result, param):
        pass
